<script setup>
import "@wangeditor/editor/dist/css/style.css";
import {
  onBeforeUnmount,
  ref,
  shallowRef,
  onMounted,
  onUpdated,
  defineProps,
  defineEmits,
} from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";

let props = defineProps({
  content: String,
  readOnly: Boolean,
});

const uploadServerUrl = `${import.meta.env.VITE_API_SERVER}`;
const emits = defineEmits(["update:content"]);
const onChange = (e) => {
  emits("update:content", e.getHtml(), e.getText());
};

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

// 内容 HTML
const valueHtml = ref(props.content);

// 模拟 ajax 异步获取内容
onMounted(() => {});

onUpdated(() => {
  valueHtml.value = props.content;
});

const toolbarConfig = {};
const editorConfig = {
  placeholder: "请输入内容...",
  MENU_CONF: {
    uploadImage: {
      server: "/ats/news/upload",
      fieldName: "file",
      allowedFileTypes: ["image/*"],
      headers: {
        Authorization: `Bearer ${localStorage.getItem("ats-user-token")}`,
      },
      customInsert(res, insertFn) {
        const url = encodeURI(
          `${uploadServerUrl}${
            res.data
          }?Authorization=Bearer ${localStorage.getItem("ats-user-token")}`
        );
        insertFn(url, "", url);
      },
    },
  },
};

// editorConfig.MENU_CONF["uploadImage"] = {
//   server: "/api/upload",
// };

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const handleCreated = (editor) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};
</script>

<template>
  <div style="border: 1px solid #ccc">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      mode="simple"
    />
    <Editor
      style="height: 500px; overflow-y: hidden"
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      mode="simple"
      @onCreated="handleCreated"
      @onChange="onChange"
    />
  </div>
</template>
